<?php
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Lib/PHPExcel.php';
class CouponController extends AppController
{
    public $name = 'Coupon';
    public $uses = array('CouponList', 'MaterialInfoList', 'MonsterAllyInfoList','CostumeinfoList','tbl_account', 'tbl_character');
    public $components = array('Paginator');
    public $paginate = array(
        'limit' => 20,
        'order' => array(
            'created' => 'DESC'
        )
    );

    public function coupon_list()
    {
        $this->Paginator->settings = $this->paginate;

        $data = $this->Paginator->paginate('CouponList');

        $this->set(compact('data'));
    }

    private function __getMaterialId()
    {
        $data = $this->MaterialInfoList->getAllId();
        $dataId = array(
            '' => '선택안함'
        );
        foreach($data as $value)
        {
            $dataId[$value['MaterialInfoList']['Id']] = $value['MaterialInfoList']['Name'];
        }

        return $dataId;
    }

    private function __getCostumeId()
    {
        $data = $this->CostumeinfoList->getAllId();
        $dataId = array(
            '' => '선택안함'
        );
        foreach($data as $value)
        {
            $dataId[$value['CostumeinfoList']['Id']] = $value['CostumeinfoList']['Name'];
        }

        return $dataId;
    }

    public function coupon_export_excel()
    {
        $data = $this->CouponList->getForExcel();

        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        foreach( $data as $num => $value){

                // Add some data
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $num, $value['CouponList']['agent'])
                    ->setCellValue('B' . $num, $value['CouponList']['coupon_id'])
                    ->setCellValue('C' . $num, $value['CouponList']['use_limit'])
                    ->setCellValue('D' . $num, $value['CouponList']['start_time'])
                    ->setCellValue('E' . $num, $value['CouponList']['end_time']);

        }

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('CouponList');

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="CoupnList.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    public function coupon_created()
    {
        $ticketId = $this->__getMaterialId();
        $this->set(compact('ticketId'));

        $costumeId = $this->__getCostumeId();
        $this->set(compact('costumeId'));

        if(!empty($this->data))
        {
            $data = $this->data['coupon_created'];

            if($data['agent'] == '')
            {
                $this->Session->setFlash('请输入礼品码种类.', 'default', array('class' => 'message'), 'bad');
                $this->set(compact('data'));
                return;
            }

            $reward['data'] = [];
            foreach($data as $key => $value)
            {
                if($key == 'reward_gold' && !empty($value))
                {
                    $reward_data = array(
                        'reward_id' => 'Gold',
                        'reward_type' => 'Gold',
                        'count' => $value,
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_crystal' && !empty($value))
                {
                    $reward_data = array(
                        'reward_id' => 'Crystal',
                        'reward_type' => 'Crystal',
                        'count' => $value,
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_friend' && !empty($value))
                {
                    $reward_data = array(
                        'reward_id' => 'Friend',
                        'reward_type' => 'Friend',
                        'count' => $value,
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_stamina' && !empty($value))
                {
                    $reward_data = array(
                        'reward_id' => 'Stamina',
                        'reward_type' => 'Stamina',
                        'count' => $value,
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_potion' && !empty($value))
                {
                    $reward_data = array(
                        'reward_id' => 'Potion',
                        'reward_type' => 'Potion',
                        'count' => $value,
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_material_1' && !empty($value) &&
                    $data['reward_material_count_1'] != '' &&
                    $data['reward_material_count_1'] > 0)
                {
                    $reward_data = array(
                        'reward_id' => $value,
                        'reward_type' => 'Material',
                        'count' => $data['reward_material_count_1'],
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_material_2' && !empty($value) &&
                    $data['reward_material_count_2'] != '' &&
                    $data['reward_material_count_2'] > 0)
                {
                    $reward_data = array(
                        'reward_id' => $value,
                        'reward_type' => 'Material',
                        'count' => $data['reward_material_count_2'],
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_material_3' && !empty($value) &&
                    $data['reward_material_count_3'] != '' &&
                    $data['reward_material_count_3'] > 0)
                {
                    $reward_data = array(
                        'reward_id' => $value,
                        'reward_type' => 'Material',
                        'count' => $data['reward_material_count_3'],
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_monster' && !empty($value) &&
                    $data['reward_monster_count'] != '' &&
                    $data['reward_monster_count'] > 0)
                {
                    $reward_data = array(
                        'reward_id' => $value,
                        'reward_type' => 'Monster',
                        'count' => $data['reward_monster_count'],
                        'expire_hour' => 0
                    );

                    $reward['data'][] = $reward_data;
                }

                if($key == 'reward_costume' && !empty($value) &&
                    $data['reward_costume_expiretime'] != '' &&
                    $data['reward_costume_expiretime'] > 0)
                {
                    $reward_data = array(
                        'reward_id' => $value,
                        'reward_type' => 'Costume',
                        'count' => 1,
                        'expire_hour' => $data['reward_costume_expiretime']
                    );

                    $reward['data'][] = $reward_data;
                }
            }

            $reward = json_encode($reward);

            App::uses('HttpSocket', 'Network/Http');
            $HttpSocket = new HttpSocket();
            $url = $this->server_url . '/coupon_created';
            
            for($num = 0; $num < $data['coupon_num']; ++$num)
            {
                $request = array(
                    'agent' => $data['agent'],
                    'use_limit' => $data['use_limit'],
                    'start_time' => $data['start_time'],
                    'end_time' => $data['end_time'],
                    'reward' => $reward,
                );

                $result = json_decode($HttpSocket->post($url, $request), true);
                if($result['rcode'] != 0)
                {
                    $this->Session->setFlash('生成失败('.($num+1).')', 'default', array('class' => 'message'), 'bad');
                    return;
                }
            }

            $this->Session->setFlash('生成完成('.$data['coupon_num'].')', 'default', array('class' => 'success'), 'good');
        }

        $this->set(compact('data'));
    }

    public function user_char_search()
    {
        $user_total_data = array();
        $user_list_db = $this->tbl_account->get_all_user();

        $objPHPExcel = new PHPExcel();

        //print_r($user_value);


        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        $user_value =  array() ;
        foreach($user_list_db as $num =>$user_value )
        {
            $char_data = $this->tbl_character->get_character($user_value['tbl_account']['_id']);

            print_r($char_data);
            echo '<br />';

            if ($char_data != null) {
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $num, $user_value['tbl_account']['account'])
                    ->setCellValue('B' . $num, $user_value['tbl_account']['platform'])
                    ->setCellValue('C' . $num, $char_data[0]['tbl_character']['nick_name'])
                    ->setCellValue('D' . $num, $char_data[0]['tbl_character']['level'])
                    ->setCellValue('E' . $num, $char_data[0]['tbl_character']['char_class'])
                    ->setCellValue('F' . $num, mongoDateToTime($user_value['tbl_account']['created']))
                    ->setCellValue('G' . $num, $char_data[0]['tbl_character']['gender'])
                    ->setCellValue('H' . $num, $user_value['tbl_account']['play_time'])
                    ->setCellValue('I' . $num, $user_value['tbl_account']['crystal']);
            }
        }

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('UserList');

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="UserList.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    function mongoDateToTime($_mongo_date, $_flag = true)
    {
        $time = 0;
        foreach($_mongo_date as $key => $value)
        {
            if($key == 'sec')
            {
                $time = $value;
                break;
            }
        }

        if($_flag == true)
        {
            return mkTimeToDate($time);
        }
        else
        {
            return $time;
        }

    }

    function mkTimeToDate($_mongo_date)
    {
        $time = date('Y-m-d H:i:s', $_mongo_date);
        return $time;
    }

}